package com.fengchao.api.controller.v1;

import com.fengchao.api.config.Constant;
import com.fengchao.api.config.WeChatConfig;
import com.fengchao.api.service.UsrService;
import com.fengchao.model.entity.comm.CustomBizException;
import com.fengchao.util.common.CommonValidator;
import com.fengchao.util.wechat.commonality.WeChatAuthUtil;
import com.fengchao.util.wechat.commonality.WeChatUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

import static com.fengchao.api.config.Constant.*;

/**
 * Created by http://my.oschina.net/wangnian on 2016/8/9.
 */
@Controller
@RequestMapping("/weixin")
public class WechatController {
    @Autowired
    private UsrService usrService;

    private Logger logger = LoggerFactory.getLogger(WechatController.class);

    /**
     * 微信获取openID
     *
     * @return
     */
    @RequestMapping(value = "/redirect/{type}", method = RequestMethod.GET)
    public String redirect(HttpServletRequest httpServletRequest,
                           @PathVariable(value = "type") String type,
                           @RequestParam String code) {
        //login //bind
        logger.info("微信回调地址 type:{} ,code:{}", type, code);
        if (!CommonValidator.isStringsNotNull(type)) {
            throw new CustomBizException(PARAMETER_IS_NOT_COMPLETE);
        }
        if ("LOGIN".equals(type.toUpperCase())) {//登陆
            Map<String, String> accessMap = WeChatAuthUtil.getAccessTokenByCode(code, WeChatConfig.LOGIN_APPID, WeChatConfig.LOGIN_APP_SECRET);
            if (accessMap.get("errcode") != null) {
                return "redirect:http://www.letswarm.com/";
            }
            String unionid = accessMap.get("unionid");
            Map<String, Object> infoMap = WeChatAuthUtil.getUserInfobyaccessToken(accessMap.get("access_token"));
            String nickName = String.valueOf(infoMap.get("nickname"));
            String sex = Double.valueOf(infoMap.get("sex").toString()) == 1 ? "男" : "女";
            String headIcon = String.valueOf(infoMap.get("headimgurl"));
            String token = usrService.loginByUserbindThirdAccount(nickName, sex, headIcon, unionid, WECHAT, httpServletRequest.getRemoteAddr(), type, null, null, null, "PC", "WEB");
            String weixinLoginUrl = Constant.CONFIGMAP.get("weixinLoginUrl");
            if (CommonValidator.isStringsNotNull(token)) {
                String base64Token = Base64Utils.encodeToString(token.getBytes());
                return "redirect:" + weixinLoginUrl + "?token=" + base64Token;
            } else {
                return "redirect:" + weixinLoginUrl;
            }
        }
        if ("BIND".equals(type.toUpperCase())) {//绑定
            Map<String, String> accessMap = WeChatAuthUtil.getAccessTokenByCode(code, WeChatConfig.LOGIN_APPID, WeChatConfig.LOGIN_APP_SECRET);
            if (accessMap.get("errcode") != null) {
                return "redirect:http://www.letswarm.com/";
            }
            String unionid = accessMap.get("unionid");
            String weixinBindUrl = CONFIGMAP.get("weixinBindUrl");
            String base64OpenId = Base64Utils.encodeToString(unionid.getBytes());
            return "redirect:" + weixinBindUrl + "?openid=" + base64OpenId;
        }
        if ("LOTTERY".equals(type.toUpperCase())) {//抽奖活动1
            String weixinLotteryUrl = CONFIGMAP.get("weixinLotteryUrl");
            Map<String, String> accessMap = WeChatAuthUtil.getAccessTokenByCode(code, WeChatConfig.APPID, WeChatConfig.APP_SECRET);
            if (accessMap.get("errcode") != null) {
                return "redirect:" + weixinLotteryUrl;
            }
            String unionid = accessMap.get("unionid");
            Map<String, Object> infoMap = WeChatAuthUtil.getUserInfobyaccessToken(accessMap.get("access_token"));
            String nickName = String.valueOf(infoMap.get("nickname"));
            String sex = Double.valueOf(infoMap.get("sex").toString()) == 1 ? "男" : "女";
            String headIcon = String.valueOf(infoMap.get("headimgurl"));
            usrService.saveUsrWechat(unionid, headIcon, nickName, sex);
            String base64OpenId = Base64Utils.encodeToString(unionid.getBytes());
            return "redirect:" + weixinLotteryUrl + "?openid=" + base64OpenId;
        }
        return "redirect:http://www.letswarm.com/";
    }

    /**
     * 获取jsSDK的配置
     *
     * @return
     */
    @RequestMapping(value = "/getJsConfig", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, String> getJsConfig(@RequestParam String url) {
        logger.info("获取jsSDK的配置");
        String jsapi_ticket = WeChatUtil.getAvailableJsapiTicket();
        return WeChatUtil.JsapiSign(jsapi_ticket, url);
    }
}
